package com.business.dashboard.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.business.dashboard.dao.AdminUserDao;
import com.business.dashboard.entity.AdminUser;
import com.business.dashboard.service.AdminUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 管理员用户服务实现类
 * 
 * @author Claude
 * @since 2025-07-06
 */
@Slf4j
@Service
@Transactional
public class AdminUserServiceImpl implements AdminUserService {

    @Autowired
    private AdminUserDao adminUserDao;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public List<AdminUser> getAllUsers() {
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("deleted", 0);
        wrapper.orderByDesc("created_at");
        return adminUserDao.selectList(wrapper);
    }

    @Override
    public AdminUser getUserById(Long id) {
        if (id == null) {
            return null;
        }
        return adminUserDao.selectById(id);
    }

    @Override
    public AdminUser getUserByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return null;
        }
        return adminUserDao.findByUsername(username);
    }

    @Override
    public AdminUser createUser(AdminUser user) {
        if (user == null) {
            throw new IllegalArgumentException("用户信息不能为空");
        }

        // 验证用户名是否已存在
        if (existsByUsername(user.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 验证邮箱是否已存在
        if (StringUtils.hasText(user.getEmail()) && existsByEmail(user.getEmail())) {
            throw new IllegalArgumentException("邮箱已存在");
        }

        // 加密密码
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        }

        // 设置默认值
        if (user.getStatus() == null) {
            user.setStatus(1);
        }
        if (user.getLoginCount() == null) {
            user.setLoginCount(0);
        }

        user.setCreatedAt(LocalDateTime.now());
        user.setUpdatedAt(LocalDateTime.now());

        int result = adminUserDao.insert(user);
        if (result > 0) {
            log.info("创建管理员用户成功，用户名: {}", user.getUsername());
            return user;
        } else {
            throw new RuntimeException("创建用户失败");
        }
    }

    @Override
    public AdminUser updateUser(AdminUser user) {
        if (user == null || user.getId() == null) {
            throw new IllegalArgumentException("用户信息或ID不能为空");
        }

        AdminUser existingUser = getUserById(user.getId());
        if (existingUser == null) {
            throw new IllegalArgumentException("用户不存在");
        }

        // 验证用户名是否已被其他用户使用
        if (StringUtils.hasText(user.getUsername()) && 
            !user.getUsername().equals(existingUser.getUsername()) && 
            existsByUsername(user.getUsername())) {
            throw new IllegalArgumentException("用户名已存在");
        }

        // 验证邮箱是否已被其他用户使用
        if (StringUtils.hasText(user.getEmail()) && 
            !user.getEmail().equals(existingUser.getEmail()) && 
            existsByEmail(user.getEmail())) {
            throw new IllegalArgumentException("邮箱已存在");
        }

        // 如果提供了新密码，进行加密
        if (StringUtils.hasText(user.getPassword())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
        } else {
            user.setPassword(null); // 不更新密码
        }

        user.setUpdatedAt(LocalDateTime.now());

        int result = adminUserDao.updateById(user);
        if (result > 0) {
            log.info("更新管理员用户成功，ID: {}", user.getId());
            return getUserById(user.getId());
        } else {
            throw new RuntimeException("更新用户失败");
        }
    }

    @Override
    public boolean deleteUser(Long id) {
        if (id == null) {
            return false;
        }

        AdminUser user = getUserById(id);
        if (user == null) {
            return false;
        }

        // 逻辑删除
        user.setDeleted(1);
        user.setUpdatedAt(LocalDateTime.now());

        int result = adminUserDao.updateById(user);
        if (result > 0) {
            log.info("删除管理员用户成功，ID: {}", id);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateUserStatus(Long id, Integer status) {
        if (id == null || status == null) {
            return false;
        }

        int result = adminUserDao.updateStatus(id, status);
        if (result > 0) {
            log.info("更新用户状态成功，ID: {}, Status: {}", id, status);
            return true;
        }
        return false;
    }

    @Override
    public boolean updateLoginInfo(Long id, String loginIp) {
        if (id == null) {
            return false;
        }

        int result = adminUserDao.updateLoginInfo(id, loginIp);
        if (result > 0) {
            log.info("更新用户登录信息成功，ID: {}, IP: {}", id, loginIp);
            return true;
        }
        return false;
    }

    @Override
    public boolean existsByUsername(String username) {
        if (!StringUtils.hasText(username)) {
            return false;
        }
        
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        wrapper.eq("deleted", 0);
        
        return adminUserDao.selectCount(wrapper) > 0;
    }

    @Override
    public boolean existsByEmail(String email) {
        if (!StringUtils.hasText(email)) {
            return false;
        }
        
        QueryWrapper<AdminUser> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        wrapper.eq("deleted", 0);
        
        return adminUserDao.selectCount(wrapper) > 0;
    }

}